package com.ase.leetcode.两数之和;

import java.util.HashMap;
import java.util.Map;

/**
 * @author gyhstart
 * @create 2021/1/7 - 22:09
 **/
public class Solution {
    /**
     * for 暴力破解法
     *
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum1(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = 1; j < nums.length; j++) {
                if (target - nums[i] == nums[j]) {
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }

    /**
     * HashMap 优化解决法
     *
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int val = target - nums[i];
            if (map.containsKey(val)) {
                return new int[]{map.get(val), i};
            }
            // map key value
            //      2    0
            map.put(nums[i], i);
        }
        return null;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{2, 7, 11, 15};
        int target = 9;

        // int[] ints = twoSum1(nums, target);
        int[] ints = twoSum2(nums, target);
        if (ints != null) {
            for (int i : ints) {
                System.out.println(i);
            }
        }
    }
}
